﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography;

namespace eLuk.CommandEngine
{
	public class ClientSecurity
	{
		public ClientSecurity()
		{ 
		
		}

		public byte[] Encrypt( byte[] PlanData )
		{
			byte[] bytes = null;
			IBuffer initVector = null;
			uint keySize = this.GetKeySize( ( uint ) PlanData.Length );
			CryptographicKey key = this.GetKey( "RSA_OAEP_SHA512", keySize );
			IBuffer buffer = null;
			IBuffer encrypted = null;
			IBuffer decrypted = null;
			if ( key != null )
			{
				try
				{
					buffer = CryptographicBuffer.CreateFromByteArray( PlanData );
					encrypted = CryptographicEngine.Encrypt( key, buffer, initVector );
					decrypted = CryptographicEngine.Decrypt( key, buffer, initVector );
					CryptographicBuffer.CopyToByteArray( encrypted, out bytes );

					if ( !CryptographicBuffer.Compare( decrypted, buffer ) )
						return null;
				}
				catch ( Exception ex )
				{
					return null;
				}
			}
			return bytes;
		}

		public byte[] Decrypt( byte[] EncryptedData )
		{
			byte[] bytes = null;
			IBuffer initVector = null;
			uint keySize = this.GetKeySize( ( uint ) EncryptedData.Length );
			CryptographicKey key = this.GetKey( "RSA_OAEP_SHA512", 2048 );
			IBuffer buffer = CryptographicBuffer.CreateFromByteArray( EncryptedData );
			IBuffer decrypted = CryptographicEngine.Decrypt( key, buffer, initVector );
			IBuffer encrypted = CryptographicEngine.Encrypt( key, buffer, initVector );
			CryptographicBuffer.CopyToByteArray( decrypted, out bytes );
			if ( !CryptographicBuffer.Compare( encrypted, buffer ) )
				return null;
			return bytes;
		}

		private uint GetKeySize( uint DataLength )
		{
			uint KeyLength = 4096;
			return KeyLength;
		}

		private CryptographicKey GetKey(string AlgorithmName, uint KeySize )
		{
			CryptographicKey keyPair;
			
			// Create an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input.
			AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm( AlgorithmName );

			// Generate a key pair.
			try
			{
				keyPair = Algorithm.CreateKeyPair( KeySize );
			}
			catch ( ArgumentException ex )
			{
				return null;
			}
			return keyPair;
		}

	}
}
